{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Control Flows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if, elif, else\n", "The basic control flows work pretty similarly in python as other languages. One thing to keep an eye out for is that **\\()** or **\\{\\}** aren't very common, instead **\\:** are used." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Python has [if, elif, else], for, while, [try, except, finally]\n", "\n", "print(\"**********\\nif, elif, and else:\") \n", "a = 3\n", "b = 5\n", "\n", "#Any control flow or function definition is capped by a :\n", "if a < b:\n", " # Note: Python is tab/whitespace delimited - meaning no {} or ;\n", " # Note 2: It is highly recommended that you setup your editor to tab using spaces, I prefer 4 space tabs!\n", " print(f\"{a} is less than {b}\")\n", "elif a == b: # 'elif' is equivalent to 'else if'\n", " print(f\"{a} equals {b}\")\n", "else:\n", " print(f\"{a} is greater than {b}\")\n", " \n", "# Lets try that again with some other numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### For loops\n", "For loops will loop through any iterator (think list, dictionary items, etc). An iterator is an object that that defines an __iter__ method, but more on that later.\n", "\n", "Essentially this means that we **don't need to index into** iterators/lists when looping through elements." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "print(\"**********\\nIterators:\") \n", "lst = [4,3,2,1]\n", "for ele in lst:\n", " print(ele) # Notice the ele variable represents the actual value, not the index\n", "\n", " \n", "# For a more traditional loop\n", "print(\"**********\\nTraditional For Loop:\") \n", "\n", "# For this we need something that generates a list of indexs, we'll use the range() function\n", "print(range(10)) # This will produce a range of values from range(init, end)\n", "\n", "for ix in range(len(lst)): #Here we loop through the index of the list\n", " # range is a generator function that will generate numbers [0, len(lst))\n", " print(lst[ix])\n", " if ix == 2: break #break command causes you to exit a loop\n", " \n", " \n", "print(\"**********\\nElements and Index:\") \n", "# For both effects we can iterate using the enumerate() function\n", "for ix, ele in enumerate(lst):\n", " print(f\"{ele} is the {ix} element\")\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Problem 1\n", "\"\"\"\n", "Given the list (lst) below, calculate the average or mean using a for loop\n", "\"\"\"\n", "lst = [23,55,2,57,9,423,4,75,8] #should get 72.88\n", "\n", "\n", "# Problem 2\n", "\"\"\"\n", "Given a list (lst), determine if a value (val) exists in the list\n", "\"\"\"\n", "lst = [32, 394, \"hello\", 312, \"Monday\", 9.0, True, \"Python\"]\n", "val = \"Monday\"\n", "\n", "\n", "# Problem 1\n", "\"\"\"\n", "Print out every even number from [50, 100] using a for loop\n", " - Hint: the range() method works like indexing (start, stop, jump)\n", "\"\"\"\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Looping through dictionaries\n", "dict.items(), dict.values(), dict.keys() - very useful and common dict methods!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# For loops with dictionaries\n", "d = {\"first\":1, \"second\":2}\n", "\n", "# dict.items returns two lists; one containing keys, the other containing the values\n", "for key, value in d.items():\n", " print(\"key - {}, value - {}\".format(key, value))\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## While loops\n", "Work exactly like in other languages, we see the loop continues until the condition is no longer true." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nWhile Loops:\")\n", "loop = 0\n", "while loop < 3:\n", " print(\"looping\")\n", " loop += 1\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Ternary Operations\n", "While ternarny should make you think 3, ternary operations in python enable us to select two options based on a conditional.\n", "\n", "$$\\text{A if condition is true else B}$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nTernary Logic:\")\n", "a=3\n", "b=5\n", "print(a if a < b else b) #returns a if condition is met, otherwise b\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Problem 1\n", "\"\"\"\n", "Given a list of integers/floats and returns the count of each element in the list.\n", "Ex. [‘a’, 4, 8, 4, ‘hello’] -> a – 1, 4 – 2, 8 – 1, ‘hello’ - 1\n", " - Hint: A Dictionary will be useful\n", "\"\"\"\n", "lst = ['a', 4, 8, 4, 'hello', 'world', 'hello', 4, 7, 3, 'a', 3]\n", "\n", "\n", "# Problem 2\n", "\"\"\"\n", "Given a list (lst) and dictionary (kv), aggregate all of the values in the dictionary where the key is in the list\n", "Ex. lst = ['a', 'b', 'f'], kv = {'a':10, 'c':5, 'f':2}, would result in 12 (a=10 and f =2 -> 12)\n", "\"\"\"\n", "lst = [24, 19, 7, 77, 48, 80]\n", "kv = {7: 23, 48: 32, 5: 2, 37: 48, 24: 13} #Should get 68\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exception handling\n", "Python uses try, except, finally for exception handling:\n", " - try: block of code we would like to run\n", " - except: block of code to execute if an exception is raised\n", " - finally: block of code that should execute regardless of flow" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "print(\"**********\\nTry Except:\")\n", "lst = ['a', 1, 5, 'hello']\n", "try:\n", " sum(lst)\n", "except:\n", " print(\"What?! Errors??\")\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nFinally:\")\n", "try:\n", " sum(lst)\n", "except:\n", " pass # pass is useful as a placeholder, where we need something, but don't have anything\n", "finally:\n", " # Finally is very useful for cleaning up or closing connections at the end of an execution\n", " print(\"Finished processing\")\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exception Handling as a Control Flow\n", "In python it is perfectly acceptable to use **try catch** logic to control the flow of execution. That being said, it shouldn't be a default." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nCatching an Error:\")\n", "lst = [123, \"b\", 3532, \"a\"]\n", "sum = 0\n", "for ele in lst:\n", " try:\n", " sum += ele\n", " except Exception as err:\n", " # Should ideally be except TypeError: to ensure we don't accidentally process different errors.\n", " print(err)\n", "print(sum)\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nCatching an Error:\")\n", "lst = [123, \"b\", 3532, \"a\"]\n", "sum = 0\n", "for ele in lst:\n", " try:\n", " sum += ele\n", " except TypeError as err: # Try changing this with SyntaxError\n", " # Should ideally be except TypeError: to ensure we don't accidentally process different errors.\n", " print(err)\n", "print(sum)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }